package cn.tedu.submarine;
import javax.swing.JFrame;
import javax.swing.JPanel;//1第一步
import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;
import java.util.Arrays;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**整个游戏世界    */
public class World extends JPanel{//2第二步
    public static final int WIDTH = 641;
    public static final int HEIGHT = 479;

    public static final int START = 0;//启动状态
    public static final int RUNNING = 1;//运行状态
    public static final int GAME_OVER = 2;//游戏结束状态
    public int state = START;//当前状态（默认为启动状态）

    private Battleship ship = new Battleship();
    private SeaObject[] submarines = {};//潜艇数组（侦察潜艇鱼雷潜艇水雷潜艇）
    private SeaObject[] thunders = {};//雷（鱼雷水雷）数组
    private Bomb[] bombs = {};//深水炸弹数组

    /**      生成潜艇（侦查潜艇鱼雷潜艇水雷潜艇）*/
    public SeaObject nextSubmarine(){
        Random rand = new Random();
        int type = rand.nextInt(20);
        if (type<10){
            return new ObserveSubmarine();
        }else if(type<15){
            return new TorpedoSubmarine();
        }else {
            return new MineSubmarine();
        }
    }
    private int subEnterIndex = 0;//潜艇入场计数
    /**潜艇入场*/
    public void submarinesEnterrAction(){//每 10毫秒走一次
        subEnterIndex++;
        if (subEnterIndex%40==0){//每400毫秒走一次（10*40）
            SeaObject obj = nextSubmarine();//
            submarines = Arrays.copyOf(submarines,submarines.length+1);
            submarines[submarines.length-1] = obj;//将obj添加到submarines的最后一个
        }
    }
    /**雷入场*/
    private  int thunderEnterIndex = 0;
    public void thunderEnterAction(){
        thunderEnterIndex++;
        if (thunderEnterIndex%100==0){//
            for (int i=0;i<submarines.length;i++){
                SeaObject obj = submarines[i].nextThunder();//获取了雷对象
                if (obj!=null){//若有雷
                    thunders = Arrays.copyOf(thunders,thunders.length+1);
                    thunders[thunders.length-1] = obj;// 将obj装到thunder
                }
            }
        }
    }
    /**海洋对象移动*/
    public void moveAction(){//每十毫秒走一次
        for (int i=0;i<submarines.length;i++){
            submarines[i].move();
        }
        for (int i=0;i<thunders.length;i++){
            thunders[i].move();
        }
        for (int i=0;i<bombs.length;i++){
            bombs[i].move();
        }
    }
    //删除越界海洋对象
   public void outOfBoundAction(){
        for (int i=0;i<submarines.length;i++){
            if (submarines[i].isOutOfBound()|| submarines[i].isDead()){
                submarines[i] = submarines[submarines.length-1];
                submarines = Arrays.copyOf(submarines,submarines.length-1);
            }
        }
        for(int i=0;i<thunders.length;i++){
            if (thunders[i].isOutOfBound()|| thunders[i].isDead()){
                thunders[i] = thunders[thunders.length-1];
                thunders= Arrays.copyOf(thunders,thunders.length-1);
            }
        }
        for (int i=0;i<bombs.length;i++){
            if (bombs[i].isOutOfBound()||bombs[i].isDead()){
                bombs[i] = bombs[bombs.length-1];
                bombs = Arrays.copyOf(bombs,bombs.length-1);
            }
        }
    }
    private int score = 0;//玩家的得分
    //深水炸弹与潜艇的碰撞
    public void bombBangAction(){//每10毫秒走一次
        for (int i=0;i<bombs.length;i++){//遍历所有渗水炸弹
            Bomb b = bombs[i];//获取每个炸弹
            for (int j=0;j<submarines.length;j++){
                SeaObject s = submarines[j];//获取每个潜艇
                if (b.isLive()&&s.isLive()&&s.isHit(b)){
                    s.goDead();//潜艇去死
                    b.goDead();//炸弹去死
                    //----判断类型得东西
                    if (s instanceof EnemyScore){//若被撞潜艇能得分
                        EnemyScore es = (EnemyScore)s;//将被撞潜艇强转为得分接口
                        score+=es.getScore();//玩家得分
                    }
                    if (s instanceof EnemyLife){//若被撞潜艇能得命
                        EnemyLife el = (EnemyLife)s;//将被撞潜艇强转为得命接口
                        int num = el.getLife();//获取命数
                        ship.addLife(num);//战舰增加命
                    }
                }
            }
        }
    }
    public void thunderBangAction(){
        for (int i=0;i<thunders.length;i++){
            SeaObject t = thunders[i];
            if(t.isLive()&&ship.isLive()&&ship.isHit(t)){
                t.goDead();
                ship.subtractiLife();//战舰减命
            }
        }
    }
    /**检测游戏结束*/
    public void checkGameOverAction(){
        if (ship.getLife()<=0){//若战舰的命数<=0,表示游戏结束了，则
            state = GAME_OVER;
        }
    }

    /** 启动程序执行*/
    public void action(){
        //键盘窃听器---
        KeyAdapter k = new KeyAdapter() {
            /**重写keyReleased（）键盘弹起时间*/
            //当按下键盘弹起时自动执行
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode()==KeyEvent.VK_SPACE){//若按下的是空格
                    switch (state){
                        case START:
                            state = RUNNING;
                            break;
                        case RUNNING:
                            Bomb obj = ship.nextBomb();//获取炸弹对象
                            bombs = Arrays.copyOf(bombs,bombs.length+1);
                            bombs[bombs.length-1] = obj;
                            break;
                        case GAME_OVER:
                            score = 0;//清理现场
                            ship = new Battleship();//对象一旦重新new，以前的对象就是垃圾了，
                            submarines = new SeaObject[0];
                            thunders = new SeaObject[0];
                            bombs = new Bomb[0];
                            state = START;
                    }
                }
                 if(e.getKeyCode()==KeyEvent.VK_LEFT){//
                     ship.moveLeft();//战舰右移
                 }
                 if (e.getKeyCode()==KeyEvent.VK_RIGHT){
                     ship.moveRight();//战舰右移
                 }
            }
        };
        this.addKeyListener(k);//添加键盘窃听器

        Timer timer = new Timer();//定时器对象
        int interval = 10;//定时间隔
        timer.schedule(new TimerTask() {
            @Override
            public void run() {//定时干的事情（）每10毫秒自动执行
                if (state == RUNNING){
                    submarinesEnterrAction();//潜艇入场
                    thunderEnterAction();//雷入场
                    moveAction();//
                    outOfBoundAction();//删除越界的海洋对象
                    bombBangAction();//深水炸弹与潜艇的碰撞
                    thunderBangAction();
                    checkGameOverAction();//检测游戏结束
                }

                repaint();//重画（系统默认重新调用paint()fangfa）
            }
        },interval,interval);//定时计划
    }
    /** 重写paint():想画图片就要重写paint*/
    public void paint(Graphics g){//每十毫秒走一次
        switch (state){//根据当前状态花不同的图
            case START://启动状态下画启动图
                Images.start.paintIcon(null,g,0,0);
                break;
            case GAME_OVER://游戏结束实画游戏结束图
                Images.gameover.paintIcon(null,g,0,0);
            case RUNNING:
                Images.sea.paintIcon(null,g,0,0);
                ship.paintImage(g);//画战舰
                for (int i=0;i<submarines.length;i++){
                    submarines[i].paintImage(g);//画潜艇
                }
                for(int i=0;i<thunders.length;i++){
                    thunders[i].paintImage(g);//画雷
                }
                for (int i=0;i<bombs.length;i++){
                    bombs[i].paintImage(g);//话深水炸弹
                }
                g.drawString("SCORE:"+score,200,50);
                g.drawString("LIFE:"+ship.getLife(),400,50);
        }
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame();//第三步
        World world = new World();
        world.setFocusable(true);
        frame.add(world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(world.WIDTH,world.HEIGHT+39);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);//1)设置窗口可见2尽快调用paint（）方法)


        world.action();



    }
}
